//
//  CYGeRenZhuYeViewController.m
//  cyydt
//
//  Created by chu on 2019/1/27.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYGeRenZhuYeViewController.h"

#import "CYGeRenZhuYe_DongTaiViewController.h"
#import "CYGeRenZhuYe_WenDaViewController.h"
#import "CYGeRenZhuYe_WenZhangViewController.h"
#import "CYGeRenZhuYe_ShiPinViewController.h"
#import "CYGeRenZhuYe_GuanWangViewController.h"
#import "CYGeRenZhuYe_XiangMuHaoZhuYeViewController.h"

#import "CYGeRenZhuYeHeaderView.h"

#import "CYPersonModel.h"
#import "CYMine_WoDeGuanZhuViewController.h"
#import "cyydt-Swift.h"


@interface CYGeRenZhuYeViewController ()<YNPageViewControllerDataSource, YNPageViewControllerDelegate, LTAdvancedScrollViewDelegate>
{
    UILabel *_titleLabel;
    UIButton *_backBtn;
    NSArray *_images;
}
@property (nonatomic, strong) UIView *navView;

@property (nonatomic, strong) CYGeRenZhuYeHeaderView *headerView;

@property (nonatomic, strong) YNPageViewController *pageVC;

@property (nonatomic, strong) CYPersonModel *personModel;

@property (nonatomic, strong) UIButton *zixunBtn;

@end

@implementation CYGeRenZhuYeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _images = @[@"wd_gezl_bg", @"rezl_bg2", @"rezl_bg3", @"rezl_bg4", @"rezl_bg5", @"rezl_bg6", @"rezl_bg7", @"rezl_bg8"];

    // Do any additional setup after loading the view.
    [self.view addSubview:self.navView];
    [self getUserInfos];
}

- (void)setupPageVC {
    
    YNPageConfigration *configration = [YNPageConfigration defaultConfig];
    configration.pageStyle = YNPageStyleSuspensionCenter;
    configration.headerViewCouldScale = NO;
    /// 控制tabbar 和 nav
    configration.showTabbar = NO;
    configration.showNavigation = NO;
    configration.scrollMenu = NO;
    configration.aligmentModeCenter = NO;
    configration.lineWidthEqualFontWidth = NO;
    configration.showBottomLine = YES;
    /// 设置悬浮停顿偏移量
    configration.suspenOffsetY = Height_NavBar;
    configration.bottomLineBgColor = RGBOF(0xe3e3e3);
    configration.lineColor = RGBOF(0xe3e3e3);
    configration.selectedItemColor = RGBOF(0xF43636);
    configration.bottomLineHeight = 1;
    configration.lineHeight = 1;
    YNPageViewController *vc = [YNPageViewController pageViewControllerWithControllers:self.getArrayVCs
                                                                                titles:[self getArrayTitles]
                                                                                config:configration];
    self.pageVC = vc;
    vc.dataSource = self;
    vc.delegate = self;

    
    vc.headerView = self.headerView;
    /// 指定默认选择index 页面
    vc.pageIndex = 0;
    
    /// 作为自控制器加入到当前控制器
    [vc addSelfToParentViewController:self];
    
    /// 如果隐藏了导航条可以 适当改y值
    //    pageVC.view.yn_y = kYNPAGE_NAVHEIGHT;
    [self.view bringSubviewToFront:self.navView];
    [self.view bringSubviewToFront:self.zixunBtn];

}

- (NSArray *)getArrayVCs {
    CYGeRenZhuYe_XiangMuHaoZhuYeViewController *xiangmuZhuYe = [[CYGeRenZhuYe_XiangMuHaoZhuYeViewController alloc] initWithItemId:self.personModel.itemId UserId:self.personModel.userId];

    CYGeRenZhuYe_DongTaiViewController *firstVC = [[CYGeRenZhuYe_DongTaiViewController alloc] initWithItemId:self.personModel.itemId UserId:self.personModel.userId];
    
    CYGeRenZhuYe_WenDaViewController *secondVC = [[CYGeRenZhuYe_WenDaViewController alloc] initWithItemId:self.personModel.itemId UserId:self.personModel.userId];
    
    CYGeRenZhuYe_WenZhangViewController *thirdVC = [[CYGeRenZhuYe_WenZhangViewController alloc] initWithItemId:self.personModel.itemId UserId:self.personModel.userId];
    
    CYGeRenZhuYe_ShiPinViewController *forthVC = [[CYGeRenZhuYe_ShiPinViewController alloc] initWithItemId:self.personModel.itemId UserId:self.personModel.userId];
    
    CYGeRenZhuYe_GuanWangViewController *fiveVC = [[CYGeRenZhuYe_GuanWangViewController alloc] init];
    fiveVC.url = self.personModel.mobileUrl;
    
    if ([self.personModel.tag isEqualToString:@"4"]) {
        [self.view addSubview:self.zixunBtn];
        //项目号
        return @[xiangmuZhuYe, secondVC, thirdVC, forthVC, fiveVC];
    }
    return @[firstVC, secondVC, thirdVC, forthVC];
}

- (NSArray *)getArrayTitles {
    if ([self.personModel.tag isEqualToString:@"4"]) {
        //项目号
        return @[@"主页", @"问答", @"文章", @"视频", @"官网"];
    }
    return @[@"动态", @"问答", @"文章", @"视频"];
}

- (UIView *)navView {
    if (!_navView) {
        _navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, Height_NavBar)];
        _navView.backgroundColor = RGBA(246, 246, 246, 0);
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, Height_StatusBar, 44, 44)];
        _backBtn = btn;
        [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(popAction:) forControlEvents:UIControlEventTouchUpInside];
        [_navView addSubview:btn];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kWindowW - 100, 44)];
        _titleLabel = label;
        label.alpha = 0;
        label.font = [UIFont systemFontOfSize:17];
        label.textAlignment = NSTextAlignmentCenter;
        label.center = CGPointMake(kWindowW / 2, Height_StatusBar + 22);
        label.textColor = [UIColor blackColor];
        [_navView addSubview:label];
    }
    return _navView;
}

- (void)popAction:(UIButton *)sender{
    [[AppDelegate sharedAppDelegate] popViewController];
}

#pragma mark - YNPageViewControllerDataSource
- (UIScrollView *)pageViewController:(YNPageViewController *)pageViewController pageForIndex:(NSInteger)index {
    UIViewController *vc = pageViewController.controllersM[index];
    if ([vc isKindOfClass:[CYGeRenZhuYe_DongTaiViewController class]]) {
        return [(CYGeRenZhuYe_DongTaiViewController *)vc tableView];
    } else if ([vc isKindOfClass:[CYGeRenZhuYe_XiangMuHaoZhuYeViewController class]]) {
        return [(CYGeRenZhuYe_XiangMuHaoZhuYeViewController *)vc tableView];
    }else if ([vc isKindOfClass:[CYGeRenZhuYe_WenDaViewController class]]) {
        return [(CYGeRenZhuYe_WenDaViewController *)vc tableView];
    }else if ([vc isKindOfClass:[CYGeRenZhuYe_WenZhangViewController class]]) {
        return [(CYGeRenZhuYe_WenZhangViewController *)vc tableView];
    }else if ([vc isKindOfClass:[CYGeRenZhuYe_ShiPinViewController class]]){
        return [(CYGeRenZhuYe_ShiPinViewController *)vc tableView];
    }else{
        CYGeRenZhuYe_GuanWangViewController *guanwang = (CYGeRenZhuYe_GuanWangViewController *)vc;
        return guanwang.WKWebView.scrollView;
    }
}

#pragma mark - YNPageViewControllerDelegate
- (void)pageViewController:(YNPageViewController *)pageViewController
            contentOffsetY:(CGFloat)contentOffset
                  progress:(CGFloat)progress {
//    NSLog(@"--- contentOffset = %f, progress = %f", contentOffset, progress);
    self.navView.backgroundColor = RGBA(246, 246, 246, progress);
    _titleLabel.alpha = progress;
    if (progress > 0.5) {
        [_backBtn setImage:[UIImage imageNamed:@"navigationbar_back"] forState:UIControlStateNormal];
    }else{
        [_backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    }
}

#pragma mark - 获取用户头部信息
- (void)getUserInfos{
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"getHead"];
    NSDictionary *param = @{@"userId2":self.userId};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"获取用户头部信息 ---- %@",responseResult);
        
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                if ([responseResult[@"data"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *data = responseResult[@"data"];
                    self.personModel = [CYPersonModel mj_objectWithKeyValues:data];
                    [self initheaderViewData];
                    if (!self.pageVC) {
                        [self setupPageVC];
                    }

                }
            }else{
                
            }
        }
    }];
}

- (void)initheaderViewData{
    [self.headerView.headImageView sd_setImageWithURL:[NSURL URLWithString:self.personModel.avatar] placeholderImage:[UIImage imageWithColor:[UIColor lightGrayColor] Size:self.headerView.headImageView.frame.size]];
    self.headerView.stateImageView.hidden = NO;
    if ([self.personModel.tag isEqualToString:@"1"]) {
        //普通
        self.headerView.stateImageView.hidden = YES;
        [self.headerView.typeLabel setBackgroundImage:[UIImage imageNamed:@"wd_gezl_pu"] forState:UIControlStateNormal];
    }else if ([self.personModel.tag isEqualToString:@"2"]){
        //导师号
        self.headerView.stateImageView.image = [UIImage imageNamed:@"wd_gezl_dsbq"];
        [self.headerView.typeLabel setBackgroundImage:[UIImage imageNamed:@"wd_gezl_dsh"] forState:UIControlStateNormal];
    }else if ([self.personModel.tag isEqualToString:@"3"]){
        //官方号
        self.headerView.stateImageView.image = [UIImage imageNamed:@"wd_gezl_gfbq"];
        [self.headerView.typeLabel setBackgroundImage:[UIImage imageNamed:@"wd_gezl_gfh"] forState:UIControlStateNormal];
    }else{
        //项目号
        self.headerView.stateImageView.image = [UIImage imageNamed:@"标签"];
        [self.headerView.typeLabel setBackgroundImage:[UIImage imageNamed:@"grzy_bqxmh"] forState:UIControlStateNormal];
    }
    self.headerView.nameLabel.text = self.personModel.username;
    [self.headerView.guanzhuCountBtn setTitle:[NSString stringWithFormat:@"%@关注",self.personModel.attentionNum] forState:UIControlStateNormal];
    [self.headerView.fensiCountBtn setTitle:[NSString stringWithFormat:@"%@粉丝",self.personModel.fansNum] forState:UIControlStateNormal];

    if ([self.personModel.userId isEqualToString:[[YLUserInfo shareUserInfo].userId stringValue]]) {
        self.headerView.guanzhuBtn.hidden = YES;
    }else{
        self.headerView.guanzhuBtn.hidden = NO;
        if ([self.personModel.isAttend isEqualToString:@"0"]) {
            //未关注
            [self.headerView.guanzhuBtn setTitle:@"+ 关注" forState:UIControlStateNormal];
        }else{
            [self.headerView.guanzhuBtn setTitle:@"已关注" forState:UIControlStateNormal];
        }
    }
    NSMutableAttributedString *introText = [[NSMutableAttributedString alloc] initWithString:self.personModel.cy_description];
    introText.yy_font = [UIFont systemFontOfSize:14];
    introText.yy_lineSpacing = 8;
    self.headerView.introLabel.attributedText = introText;
    _titleLabel.text = self.personModel.username;
}

#pragma mark - 关注
- (void)guanzhu{
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"attention"];
    NSDictionary *param = @{@"toUserId":self.personModel.userId};
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"添加关注 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [[UIApplication sharedApplication].keyWindow makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                //                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                [self getUserInfos];
            }else{
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (void)cancleguanzhu{
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@/%@",User_HOST, @"attention", self.personModel.userId];
    NSDictionary *param = @{@"userId":self.personModel.userId};
    [[XBRequest sharedInstance] deleteDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"取消关注 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [[UIApplication sharedApplication].keyWindow makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                //                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                [self getUserInfos];
            }else{
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (CYGeRenZhuYeHeaderView *)headerView{
    if (!_headerView) {
        NSArray *nibView =  [[NSBundle mainBundle] loadNibNamed:@"CYGeRenZhuYeHeaderView" owner:self options:nil];
        _headerView = [nibView objectAtIndex:0];
        if (HX_IS_IPhoneX_All) {
            _headerView.frame = CGRectMake(0, 0, kWindowW, 240 + Height_StatusBar);
            _headerView.backViewHeightConstraint.constant = 240 + Height_StatusBar;
        }else{
            _headerView.frame = CGRectMake(0, 0, kWindowW, 260);
            _headerView.backViewHeightConstraint.constant = 260;

        }
        _headerView.headImageMarginTopConstraint.constant = Height_NavBar;
        if ([self.userId integerValue] == [[YLUserInfo shareUserInfo].userId integerValue]) {
            NSInteger tag = [[YLUserInfo shareUserInfo].background integerValue] - 1;
            if (tag >= _images.count) {
                _headerView.backImageView.image = [UIImage imageNamed:[_images lastObject]];
            }else{
                _headerView.backImageView.image = [UIImage imageNamed:_images[tag]];
            }
        }
        _headerView.backgroundColor = BackGroundColor;
        _headerView.backView.backgroundColor = BackGroundColor;
        __weak typeof(self)weakself = self;
        __weak typeof(_headerView)weakhead = _headerView;

        _headerView.block = ^(CGFloat bottomHeight) {
            weakhead.frame = CGRectMake(0, 0, kWindowW, 240 + Height_StatusBar - 45 + bottomHeight);
            weakhead.backViewHeightConstraint.constant = 240 + Height_StatusBar - 45 + bottomHeight;
            [weakself.pageVC reloadSuspendHeaderViewFrame];

        };
        
        _headerView.guanzhuBlock = ^{
            if ([weakself.personModel.isAttend isEqualToString:@"0"]) {
                [weakself guanzhu];
            }else{
                [weakself cancleguanzhu];
            }
        };
        
        _headerView.fensiBlock = ^(NSInteger tag) {
            
            CYMine_WoDeGuanZhuViewController *guanzhu = [[CYMine_WoDeGuanZhuViewController alloc] init];
            guanzhu.uid = weakself.personModel.userId;
            guanzhu.tag = tag;
            [[AppDelegate sharedAppDelegate] pushViewController:guanzhu];
        };
    }
    return _headerView;
}

- (UIButton *)zixunBtn{
    if (!_zixunBtn) {
        _zixunBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_zixunBtn setAdjustsImageWhenHighlighted:NO];
        _zixunBtn.frame = CGRectMake(kWindowW - 70, kWindowH - 150, 50, 50);
        [_zixunBtn setImage:[UIImage imageNamed:@"grzy_zx"] forState:UIControlStateNormal];
        [_zixunBtn addTarget:self action:@selector(zixunAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _zixunBtn;
}

- (void)zixunAction:(UIButton *)sender{
    CYChatViewController *chat = [[CYChatViewController alloc] init];
    chat.url = [NSString stringWithFormat:@"%@?device=ios",self.personModel.wsurl];
    [[AppDelegate sharedAppDelegate] pushViewController:chat];
}

@end
